package com.luowenbo.shortlink.separation.task;

import com.luowenbo.shortlink.separation.entity.UrlMap;
import com.luowenbo.shortlink.separation.service.impl.UrlMapServiceImpl;
import com.luowenbo.shortlink.server.infra.common.TimeZoneConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.Instant;
import java.time.OffsetDateTime;
import java.util.List;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

@Component
public class ColdAndHotSeparationTask {

    @Autowired
    private UrlMapServiceImpl urlMapService;

    @Scheduled(cron = " 0 * * * * ?")     //每天凌晨俩点触发,目前测试一分钟一次
    public void ColdAndHotSeparationTask() {
//        long timeMillis = System.currentTimeMillis() - (1000 * 60 * 60 * 24 * 30);
        long timeMillis = System.currentTimeMillis() - (1000 * 60 * 60);
        OffsetDateTime time = OffsetDateTime.ofInstant(Instant.ofEpochMilli(timeMillis), TimeZoneConstant.CHINA.getZoneId());
        int count = urlMapService.findColdDataCountInHot(time);;
        if (count == 0) {
            return;
        }
        int i1 = urlMapService.updateColdFlagInHot(time);
        int threadNum = 10;
        if ((count / 100) + 1 < threadNum) {
            threadNum = (count / 100) + 1;
        }
        ThreadPoolExecutor threadPoolExecutor = new ThreadPoolExecutor(threadNum, threadNum, 60, TimeUnit.MINUTES, new ArrayBlockingQueue<>(10), new ThreadPoolExecutor.CallerRunsPolicy());
        for(int i = 0; i < threadNum; i++){
            Runnable runnable = () -> {
                //	update lockthread = curThread  where coldflag && （lockthread == null || lockTime超时） limit 100
                urlMapService.AtomicUpdateLockThread(Thread.currentThread().getName(), OffsetDateTime.ofInstant(Instant.ofEpochMilli(System.currentTimeMillis() - (1000 * 60 * 10)), TimeZoneConstant.CHINA.getZoneId()));
                List<UrlMap> coldData = urlMapService.getDataByThread(Thread.currentThread().getName());
                urlMapService.insertColdDataToColdDB(coldData);
                urlMapService.deleteColdDataInHotDB(Thread.currentThread().getName());
            };
            threadPoolExecutor.execute(runnable);
        }
        threadPoolExecutor.shutdown();
        while (!threadPoolExecutor.isTerminated()) {
        }
    }
}
